import scala.actors._
import scala.util.Random

/**
 * DocumentCheck takes Passenger and Baggage (is this still the case?) messages
 * and sends them to the various queues for each line. It also rejects
 * Passengers for "documentation problems" 20% of the time.
 * @author Samuel Nelson, Robert Vrooman, James Fitzgerald, Gabriel Marcano
 */
class DocumentCheck(numLines: Int, jail: Jail) extends Actor {

  val random = new Random
  val lines = new Array[Queue](numLines)
  
  jail.start()
  // Start up each line
  for (i <- 0 to numLines - 1) {
    val security = new Security(i, jail)
    val bagScan = new BagScan(i, security)
    val bodyScan = new BodyScan(i, security)
    lines(i) = new Queue(i, bagScan, bodyScan)
    lines(i).start
    bagScan.start
    bodyScan.start
    security.start
  }
  var lastLine = 0

  def act() {
    loop {
      reactWithin(100) {
        case Startup =>
          println("Document Check received Startup.")
          for (i <- 0 to numLines - 1)
            lines(i) ! Startup
        case passenger: Passenger => {
            println("DocumentCheck received Passenger " + passenger.ID + ".")
            // Passenger entered the document check line. Reject their documents
            // at 20% chance
            if (random.nextDouble < .20) {
              println("Passenger " + passenger.ID +
                      " was turned away at DocumentCheck.")
            } else {
              println("DocumentCheck is sending Passenger " + passenger.ID +
                      " to Queue " + lastLine + ".");
              lines(lastLine) ! passenger
              lastLine = (lastLine + 1) % numLines;
            }
          }
        case Shutdown =>
          println("DocumentCheck has received Shutdown.")
          shutdownRequested
          
        case TIMEOUT =>
          println("DocumentCheck has determined that there is nothing else " 
                  + "to do, shutting the system down.")
          for (i <- 0 to numLines - 1){
            println("Sending Shutdown to Queue " + i + ".")
            lines(i) ! Shutdown
          }
          println("DocumentCheck has now shutdown.")
          exit
      }
    }
  }
  
  def shutdownRequested : Nothing = reactWithin(0){
    case Shutdown =>{
        shutdownRequested
      }
    case TIMEOUT =>{
   
        for (i <- 0 to numLines - 1){
            println("Sending Shutdown to Queue " + i + ".")
            lines(i) ! Shutdown
          }
        println("DocumentCheck has now shutdown.")
        exit
      }
  }
}